import { PageLoading } from '@ant-design/pro-layout';
import { notification, Button } from 'antd';
import { history, Link } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import { currentUser as queryCurrentUser, getAdminUserMenu } from './services/ant-design-pro/api';
import { BookOutlined, LinkOutlined } from '@ant-design/icons';

const isDev = process.env.NODE_ENV === 'development';

const loginPath = '/user/login';
/** 获取用户信息比较慢的时候会展示一个 loading */

export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */

// 模拟后台取得的api 数据
// const menuDatas = [
//   {
//     path: '/members',
//     name: '用户管理',
//     routes: [
//       {
//         path: '/members/member',
//         name: '用户管理',
//         icon: 'smile',
//       },
//       {
//         path: '/members/memberLog',
//         name: '用户日志',
//         icon: 'smile',
//         component: './members/memberLog',
//       },
//     ],
//   },
// ];

console.log('process.env.NODE_ENV', process.env.NODE_ENV)
// if (process.env.NODE_ENV == "development") {
//   // alert("开发环境")
// }else{
//   // alert("生产环境")
// }

export async function getInitialState() {
  // 如果没有token，跳转到登录页面
  if (!localStorage.getItem('access_token')) {
    history.push(loginPath);
  }

  // 如果是登录页面，不执行
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser();
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }

    return undefined;
  };

  if (history.location.pathname !== loginPath) {
    // 获取用户信息
    const currentUser = await fetchUserInfo();

    return {
      fetchUserInfo,
      currentUser,
      settings: {},
    };
  }

  return {
    fetchUserInfo,
    settings: {},
  };
} // ProLayout 支持的api https://procomponents.ant.design/components/layout

const loopMenuItem = (menus = []) =>
  menus.map(({ icon, children, ...item }) => {
    return {
      ...item,
      path: item.menu_path,
      name: item.menu_name,
      routes: children ? loopMenuItem(children) : [],
    };
  });

export const layout = ({ initialState }) => {
  return {
    menu: {
      locale: false,
      // 每当 initialState?.currentUser?.userid 发生修改时重新执行 request
      params: initialState,
      request: async (params, defaultMenuData) => {
        if (params.currentUser?.admin_user_id){
          const res = await getAdminUserMenu();
          return loopMenuItem(res.data);
        }
      },
    },
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    // footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history; // 如果没有登录，重定向到 login

      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    links: isDev
      ? [
        <div>
          <LinkOutlined />
          <a href="https://miren123.gitee.io/mi-admin-docs/" target="_blank" rel="noreferrer" style={{marginLeft: '10px'}}>
            Open 开发文档
          </a>
        </div>
        ]
      : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
  };
};

const authHeaderInterceptor = (url, options) => {
  const token = localStorage.getItem('access_token') || '';
  const authHeader = { AdminToken: `${token}` };
  return {
    url: `${url}`,
    options: { ...options, interceptors: true, headers: authHeader },
  };
};

const demoResponseInterceptors = async (response, options) => {
  // response.headers.append('interceptors', 'yes yo');
  const result = await response.json();
  if (result.code === 401) {
    notification.error({
      description: result.msg,
      message: '操作提示',
    });
    history.push(loginPath);
  } else if (result.code === 400) {
    notification.error({
      description: result.msg,
      message: '操作提示',
    });
  } else if (result.code === 403) {
    notification.error({
      description: result.msg,
      message: '操作提示',
    });
  } else if (result.code === 404) {
    notification.error({
      description: result.msg,
      message: '操作提示',
    });
  } else if (result.code === 429) {
    notification.error({
      description: result.msg,
      message: '操作提示',
    });
  } else if (result.code === 500) {
    notification.error({
      description: result.msg,
      message: '操作提示',
    });
  }

  return result;
};

export const request = {
  errorHandler: (error) => {
    const { response } = error;

    if (!response) {
      notification.error({
        description: '您的网络发生异常，无法连接服务器',
        message: '网络异常',
      });
    }

    throw error;
  },
  requestInterceptors: [authHeaderInterceptor],
  responseInterceptors: [demoResponseInterceptors],
}; // ProLayout 支持的api https://procomponents.ant.design/components/layout
